<script setup lang="ts">
import * as Yup from 'yup'
import NoGetCode from '../../verify/_com/NoGetCode.vue'

interface Props {
  isOpen?: boolean
  close?: () => void
}
defineOptions({
  name: 'ResolveLocked',
})
defineProps<Props>()

const $t: any = inject('i18n')

const { countryCallingCode } = useIpApi()
const { areaCodeOptionsFiltered } = useAreaCode()
const { runAsync: runResolveLocked } = useRequest(ApiMemberUnlock)

const isCountdown = ref(false)
const { start, reset, current } = useCountDown({
  time: 60 * 1000,
  onFinish() {
    isCountdown.value = false
  },
})

const schema = Yup.object().shape({
  username: Yup.string(),
  account: Yup.string(),
  verifyCode: Yup.string(),
})
const areaCode = ref(countryCallingCode.value)
const username = ref('')
const account = ref('')
const verifyCode = ref('')
const isCode = ref(false)
const isPop = ref(false)
const isPhoOrEma = ref<'p' | 'e'>('e')
const isFirst = ref(true)

function isWhat(value: string) {
  account.value = value
  if (value.length < 3) {
    isPhoOrEma.value = 'e'
    return
  }
  if (numberReg.test(value)) {
    isPhoOrEma.value = 'p'
  }
  else {
    isPhoOrEma.value = 'e'
  }
}
function Resend() {
  reset()
  start()
  isCountdown.value = true
}
async function onSelfSend() {
  const userRes = await onValidUserName(username.value)
  const accountRes = await onValidAccount(account.value)
  if (userRes || accountRes) {
    message.error(userRes || accountRes)
    return
  }
  const params = {
    username: username.value,
    [isPhoOrEma.value ? 'email' : 'phone']: isPhoOrEma.value ? account.value : `${areaCode.value}-${account.value}`,
    captcha: '',
  }
  runResolveLocked(params).then(() => {
    if (isFirst.value) {
      isFirst.value = false
    }
    Resend()
  })
}
async function onValidUserName(user: string) {
  if (user.length < 3)
    return $t('pop_up_login_first_input_min_length', { delta: 3 })
  else if (user.length > 30)
    return $t('max_len_char', { delta: 30 })
  else if (user.match('[^@.a-zA-Z0-9_]'))
    return $t('name_has_invalid_char')
  else if (!emailReg.test(user) && !usernameReg.test(user))
    return $t('validate_msg_user_name')
  return ''
}
async function onValidAccount(value: string) {
  if (!value) {
    return $t('pls_enter_email_address') + $t('or') + $t('phone')
  }
  if (isPhoOrEma.value === 'e') {
    return emailReg.test(value) ? '' : $t('email_address_incorrect')
  }
  else if (startWithNumber.test(value)) {
    if (areaCode.value === '+63')
      return philippinePhoneReg.test(`+63${value}`) && value.length > 5 && value.length <= 18 ? '' : $t('phone_invalid')
    else if (areaCode.value === '+86')
      return chinaPhoneReg.test(`${value}`) && value.length > 5 && value.length <= 18 ? '' : $t('phone_invalid')
    else if (areaCode.value === '+55')
      return brazilPhoneReg.test(`+55${value}`) && value.length > 5 && value.length <= 18 ? '' : $t('phone_invalid')
    return numberReg.test(value) && value.length > 5 && value.length <= 18 ? '' : $t('phone_invalid')
  }
  return ''
}
async function onValidCode(value: string) {
  if (!payPasswordReg.test(value))
    return isPhoOrEma.value ? $t('validate_msg_regexp_code') : $t('validate_msg_regexp_code_phone')
  return ''
}

async function onResolve(values: any) {
  const userRes = await onValidUserName(values.username)
  const accountRes = await onValidAccount(values.account)
  const codeRes = await onValidCode(values.verifyCode)
  if (userRes || accountRes || codeRes) {
    message.error(userRes || accountRes || codeRes)
    return
  }
  const params = {
    username: username.value,
    [isPhoOrEma.value ? 'email' : 'phone']: isPhoOrEma.value ? account.value : `${areaCode.value}-${account.value}`,
    captcha: verifyCode.value,
  }
  runResolveLocked(params).then(() => {
    message.success($t('your_account_already_resolve_lock'))
    close()
  })
}
function onInvalidSubmit() {

}
</script>

<template>
  <div>
    <BaseForm :schema="schema" autocomplete="off" @submit="onResolve" @invalid-submit="onInvalidSubmit">
      <BaseInput
        name="username"
        class="mt-3"
        :placeholder="$t('username')"
        :required="true"
        @update:model-value="v => (username = v)"
      />
      <BaseInput
        name="account"
        class="mt-3"
        :model-value="account"
        :placeholder="$t('emailOrPhone')"
        :required="true"
        @update:model-value="isWhat"
      >
        <template #left-icon>
          <BaseButton v-if="isPhoOrEma == 'p'" type="none" class="text-[0.75rem] !p-0" @click="isPop = true">
            <div class="border-r-[2px] border-[#e4eaf019] pr-1 flex">
              {{ areaCode }}<BaseIcon name="uni-arrow-down" class="pl-1" />
            </div>
          </BaseButton>
        </template>
      </BaseInput>
      <BaseInput
        name="verifyCode"
        required
        class="mt-3"
        :placeholder="$t('verify_code')"
        @update:model-value="v => (verifyCode = v)"
      >
        <template #right-icon>
          <BaseButton
            v-if="isCountdown"
            disabled
            class="bg-[#3A4142] text-[#B3BEC1] text-sm h-8 p-1.5 -mr-1 font-bold rounded-lg"
            type="none"
            style="box-shadow: 0px -2px 0px 0px #323738 inset"
          >
            {{ current.seconds }}S {{ $t('send_again') }}
          </BaseButton>
          <BaseButton
            v-else
            class="text-sm h-8 p-1.5 -mr-1 font-bold rounded-lg"
            @click="onSelfSend"
          >
            <!-- get_code 获取验证码 -->
            {{ isFirst ? $t('get_code') : $t('resend') }}
          </BaseButton>
        </template>
      </BaseInput>
      <div>
        <BaseButton type="none" class="text-[#24EE89] text-xs font-semibold" @click="() => isCode = true">
          {{ $t('no_get_code') }}
        </BaseButton>
      </div>
      <BaseButton html-type="submit" class="text-xs w-full font-semibold">
        {{ $t('submit') }}
      </BaseButton>
    </BaseForm>

    <div>
      <BaseBob v-model:show="isPop" isSearch v-model:selected="areaCode" :header="$t('area_choice')" :need-move="true" :option="areaCodeOptionsFiltered" />
      <BaseBob v-model:show="isCode" :header="$t('no_get_code')">
        <NoGetCode />
      </BaseBob>
    </div>
  </div>
</template>
